package org.algorithm;

import org.apache.cassandra.utils.Hex;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class Hmac {

    private static String hmac(String nonce, String password, String algorithm) throws Exception {
        if ( password == null) {
            return null;
        }
        byte[] hmacResult = null;
        Mac mac = Mac.getInstance(algorithm);
        SecretKeySpec secretKeySpec = new SecretKeySpec(password.getBytes(), algorithm);
        mac.init(secretKeySpec);
        hmacResult = mac.doFinal(nonce.getBytes());
        System.out.println("hex结果:"+ Hex.bytesToHex(hmacResult));
        return Base64.getEncoder().withoutPadding().encodeToString(hmacResult);
    }
    public static String hmacSha256(String nonce, String password) throws Exception {
        return hmac(nonce,password,"HmacSHA256");
    }

    public static void main(String[] args) throws Exception {
        String password = "nc3fqd9x6ekpdslx48iwusoa";
        // 2. 加密字符串
        String originalText = "AbISZAAW";
        String encryptedText = hmacSha256(originalText, password);
        System.out.println("Encrypted Text:" + encryptedText);
    }
}
